<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="卡片名称" prop="cardName">
        <el-input
          v-model="queryParams.cardName"
          placeholder="请输入卡片名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item class="search">
        <hide-search :show-search.sync="showSearch"></hide-search>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-content">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['project:card:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="cardList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="卡片名称" align="center" prop="cardName" />
        <el-table-column label="卡片价格" align="center" width="120" prop="cardPrice" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['project:card:create']"
              size="mini"
              icon="el-icon-edit"
              @click="handleCreate(scope.row)"
            >制卡</el-button>
            <el-button
              v-hasPermi="['project:card:export']"
              size="mini"
              icon="el-icon-edit"
              @click="handleExport(scope.row)"
            >导出卡片</el-button>
            <el-button
              v-hasPermi="['project:card:view']"
              size="mini"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row, 'view')"
            >详情</el-button>
            <el-button
              v-hasPermi="['project:card:edit']"
              size="mini"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row, 'edit')"
            >修改</el-button>
            <el-button
              v-hasPermi="['project:card:remove']"
              size="mini"
              icon="el-icon-delete"
              class="btn-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改卡片对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="卡片名称" prop="cardName">
              <el-input v-model="form.cardName" placeholder="请输入卡片名称" :disabled="openStatus === 'view'"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卡片价格" prop="cardPrice">
              <el-input-number
                v-model="form.cardPrice"
                :precision="2"
                :min="0"
                placeholder="请输入卡片价格"
                style="width: 100%"
                :disabled="openStatus === 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="openStatus === 'view'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="openStatus === 'view'">
          <el-col :span="24">
            <el-table
              v-loading="loading"
              :data="cardListList"
            >
              <el-table-column type="index" label="序号" width="55"  align="center" />
              <el-table-column label="卡密"  align="center" prop="id" width="200" show-overflow-tooltip/>
              <el-table-column label="二维码" align="center" prop="qrCode">
                <template #default="scope">
                  <img
                    v-if="scope.row.qrCode"
                    :src="'data:image/png;base64,' + scope.row.qrCode"
                    alt="二维码"
                    style="width: 80px; height: 80px;"
                  />
                </template>
              </el-table-column>
              <el-table-column label="归属用户"  align="center" prop="nickName" show-overflow-tooltip/>
              <el-table-column label="状态"  align="center" prop="active" show-overflow-tooltip>
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.card_status" :value="scope.row.active"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100" fixed="right">
                <template slot-scope="scope">
                  <div style="text-align:right">
                    <el-button
                      v-hasPermi="['project:cardList:remove']"
                      size="mini"
                      class="btn-delete"
                      icon="el-icon-delete"
                      @click="handleDeleteDetail(scope.row)"
                    >删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="cardTotal>0"
              :total="cardTotal"
              :page.sync="queryDetailParams.pageNum"
              :limit.sync="queryDetailParams.pageSize"
              @pagination="getDetailList"
            />
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 制卡对话框 -->
    <el-dialog :title="title" :visible.sync="cardOpen" width="500px" append-to-body>
      <el-form ref="cardForm" :model="cardForm" :rules="cardRules" label-width="90px">
        <el-form-item label="卡片名称" prop="cardName">
          <el-input v-model="cardForm.cardName" placeholder="请输入卡片名称" />
        </el-form-item>
        <el-form-item label="卡片价格" prop="cardPrice">
          <el-input-number
            v-model="cardForm.cardPrice"
            :precision="2"
            :min="0"
            placeholder="请输入卡片价格"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="数量" prop="cardNum">
          <el-input-number v-model="cardForm.cardNum" :min="1" :step="1" placeholder="请输入数量" style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCardForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCard, getCard, addCard, updateCard, delCard } from "@/api/card";
import {addCardList, delCardList, listCardList} from "../../../api/cardList";
export default {
  name: "Card",
  dicts: ["card_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 实体卡列表总条数
      cardTotal: 0,
      // 品牌表格数据
      cardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 制卡
      cardOpen: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cardName: undefined,
        cardPrice: undefined,
        remark: undefined
      },
      queryDetailParams: {
        pageNum: 1,
        pageSize: 10,
        cardId: undefined,
      },
      // 表单参数
      form: {},
      // 制卡表单参数
      cardForm: {},
      // 表单校验
      rules: {
        cardName: [
          { required: true, message: "卡片名称不能为空", trigger: "blur" }
        ],
        cardPrice: [
          { required: true, message: "卡片价格不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "备注不能为空", trigger: "blur" }
        ]
      },
      // 制卡表单校验
      cardRules: {
        cardNum: [
          { required: true, message: "数量不能为空", trigger: "blur" },
          { type: "number", min: 1, message: "数量必须大于0", trigger: "blur" }
        ]
      },
      // 显示弹状态 edit view
      openStatus: "view",
      cardListList: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询品牌列表 */
    async getList() {
      this.loading = true;
      listCard(this.queryParams).then(response => {
        console.log("response ---- ", response)
        this.cardList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.cardOpen = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.cardForm = {
        cardId: undefined,
        cardName: undefined,
        cardPrice: undefined,
        cardNum: 1
      };
      this.form = {
        cardName: undefined,
        cardPrice: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.openStatus = "add";
      this.title = "添加卡";
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 制卡按钮 */
    handleCreate(row) {
      this.reset();
      this.title = "制卡";
      this.cardOpen = true;
      this.cardForm = {
        cardId: row.id,
        cardName: row.cardName,
        cardPrice: row.cardPrice,
        cardNum: 1
      }
    },

    /** 导出卡片 */
    handleExport(row) {
      this.download('/project/cardList/export', {
        row
      }, `card_${new Date().getTime()}.zip`)
    },

    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.loading = true;
      this.openStatus = type;
      this.reset();
      const id = row.id || this.ids
      getCard(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.queryDetailParams.cardId = response.data.id;
        this.getDetailList();
        this.open = true;
        this.title = type === "view" ? "查看卡片" : "修改卡片";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async(valid) => {
        console.log("valid ---- ", valid);
        if (valid) {
          console.log("form ---- ", this.form);
          try {
            if (this.form.id != undefined) {
              await updateCard(this.form);
              this.$modal.msgSuccess("修改成功");
            } else {
              await addCard(this.form);
              this.$modal.msgSuccess("新增成功");
            }
            this.open = false;
            this.getList();
          } catch (error) {
            console.error("提交失败:", error);
            this.$modal.msgError("操作失败");
          }
        }
      });
    },

    /** 制卡 */
    submitCardForm() {
      this.$refs["cardForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          addCardList(this.cardForm).then(response => {
            this.$modal.msgSuccess("制卡成功");
            this.cardOpen = false;
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      console.log("del ----- ", row)
      const cardIds = row.id || this.ids;
      this.$modal.confirm("是否确认删除？").then(() => {
        return delCard(cardIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 删除实体卡按钮操作 */
    handleDeleteDetail(row) {
      this.$modal.confirm('是否确认删除卡密为"' + row.id + '"的数据项？').then(() => {
        this.loading = true;
        return delCardList(row.id);
      }).then(() => {
        this.loading = false;
        listCardList(row.cardId).then(response => {
          this.form.details = response.rows;
          this.cardTotal = response.total;
        })
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 查询实体卡列表 */
    getDetailList() {
      this.loading = true;
      listCardList(this.queryDetailParams).then(response => {
        this.cardListList = response.rows;
        this.cardTotal = response.total;
        this.loading = false;
      });
    },

    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      // 实现刷新缓存逻辑
      this.$modal.msgSuccess("刷新成功");
    }
  }
};
</script>
